import {reqLogin} from "../../request/api"
// 初始值
const initState = {
    // 初始化user
    user: {
        phone: "",
        password: ""
    },
    info:sessionStorage.getItem("user")?JSON.parse(sessionStorage.getItem("user")):{}
}

// actionsTypes
const types = {
    // 修改user type
    CHANGE_USER: "LOGIN_CHANGE_USER",
    CHANGE_INFO: "LOGIN_CHANGE_INFO",
}

// reducer 修改数据
const reducer = (state = initState, action) => {
    switch (action.type) {
        case types.CHANGE_USER:
            return {
                ...state,
                user: {
                    ...state.user,
                    [action.key]: action.value
                }
            }
        case types.CHANGE_INFO:
            return {
                ...state,
                info: action.info
            }
        default:
            return state;
    }

}

// actionCreators组件派发的动作
export const actions={
    // 修改user的action
    changeUser:(key,value)=>({type:types.CHANGE_USER,key,value}),
    changeInfo:(info)=>{
        if(info.token){
            sessionStorage.setItem("user",JSON.stringify(info))
        }else{
            sessionStorage.removeItem("user")
        }
        return {type:types.CHANGE_INFO,info}
    },
    // 注册请求
    reqLogin:(history)=>(dispatch,getState)=>{
        let { user } = getState().login;
        reqLogin(user).then(res => {
            if (res.data.code === 200) {
                dispatch(actions.changeInfo(res.data.list));
                
                //跳转页面
                history.push("/index/home")
            }
        })
    }
}

//selectors导出数据 
export const getUser=state=>state.login.user;
  
export default reducer